/*
 * SplashScreen.java - Splash screen
 */

package org.lex.swing.widgets;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;

import javax.swing.JComponent;
import javax.swing.JWindow;

/**
 * The splash screen displayed on startup.
 */
public class SplashScreen2 extends JComponent {
	private static final int PROGRESS_HEIGHT = 20;

	// private members
	private FontMetrics fm;

	private Image image;

	private int progress;

	private JWindow win;

	public SplashScreen2() {
		setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		setBackground(Color.white);

		Font font = new Font("Dialog", Font.PLAIN, 10);
		setFont(font);
		fm = getFontMetrics(font);

		image = getToolkit().getImage(getClass().getResource("/org/gjt/sp/jedit/icons/splash.png"));
		MediaTracker tracker = new MediaTracker(this);
		tracker.addImage(image, 0);

		try {
			tracker.waitForAll();
		} catch (Exception e) {
		}

		win = new JWindow();

		Dimension screen = getToolkit().getScreenSize();
		Dimension size = new Dimension(image.getWidth(this) + 2, image.getHeight(this) + 2 + PROGRESS_HEIGHT);
		win.setSize(size);

		win.getContentPane().add(BorderLayout.CENTER, this);

		win.setLocation((screen.width - size.width) / 2, (screen.height - size.height) / 2);
		win.validate();
		win.setVisible(true);

		/*
		 * synchronized(this) { try { wait(); } catch(InterruptedException ie) {
		 * Log.log(Log.ERROR,this,ie); } }
		 */
	}

	public synchronized void advance() {
		progress++;
		repaint();

		// wait for it to be painted to ensure progress is updated
		// continuously
		try {
			wait();
		} catch (InterruptedException ie) {
		}
	}

	public void dispose() {
		win.dispose();
	}

	public synchronized void paintComponent(Graphics g) {
		Dimension size = getSize();

		g.setColor(Color.black);
		g.drawRect(0, 0, size.width - 1, size.height - 1);

		g.drawImage(image, 1, 1, this);

		// XXX: This should not be hardcoded
		g.setColor(Color.white);
		g.fillRect(1, image.getHeight(this) + 1, ((win.getWidth() - 2) * progress) / 5, PROGRESS_HEIGHT);

		g.setColor(Color.black);

		String str = "VERSION 4.2 final";

		g.drawString(str, (getWidth() - fm.stringWidth(str)) / 2, image.getHeight(this) + (PROGRESS_HEIGHT + fm.getAscent() + fm.getDescent()) / 2);

		notify();
	}
}
